package com.eques.demo

import android.os.Bundle
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.eques.base.BaseActivity
import com.eques.bean.RingRecord
import com.eques.demo.adapter.RingRecordAdapter
import com.eques.util.Config
import com.eques.util.DateTimeUtil
import com.eques.util.HttpUtil
import org.json.JSONObject
import java.util.Date

class RingRecordListActivity : BaseActivity() {
    private lateinit var recyclerView: RecyclerView
    private lateinit var adapter: RingRecordAdapter
    private lateinit var tvEmpty: TextView

    private val REQUEST_METHOD_PIR = "get_device_alarm"
    private val REQUEST_METHOD_VISITOR = "get_device_ring"

    private var devId: String = ""
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_ring_record_list)
        devId = intent.getStringExtra("devId").toString()
        initView()
    }

    override fun initView() {
        recyclerView = findViewById(R.id.recyclerView)
        tvEmpty = findViewById(R.id.tv_empty)

        // 设置标题
        findViewById<TextView>(R.id.tv_title).text = "门铃记录"
        setupRecyclerView()
        getRing()
    }

    private fun setupRecyclerView() {
        adapter = RingRecordAdapter()
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.adapter = adapter

        // 设置点击监听
        adapter.onItemClickListener = { record ->
            // 处理item点击，比如跳转到详情页面
            showRecordDetail(record)
        }
    }

    override fun initData() {
    }


    fun getRing() {
        var startAndEndDate = DateTimeUtil.getCurrDate()
        var startTime = java.lang.String.valueOf(
            DateTimeUtil.getSpecifiedDateTime_000000(startAndEndDate).time
        )
        var endTime = java.lang.String.valueOf(
            DateTimeUtil.getSpecifiedDateTime_235959(startAndEndDate).time
        )
        var host = preference.getMainUrl()
        val token = preference.getString(Config.EQUES_USER_TOKEN)
        val uid = preference.getString(Config.EQUES_USER_UID)
        val url = Config.getVisitorMessageListUrl(
            host,
            REQUEST_METHOD_VISITOR,
            uid,
            token,
            devId,
            startTime,
            endTime,
            "0",
            "1000"
        )
        println("GET Ring url: $url")
        HttpUtil.getAsync(
            url = url.toString(),
        ) { result ->
            result.onSuccess { response ->
                println("GET Ring Response: $response")
                runOnUiThread {
                    parseAndDisplayData(response)
                }

            }.onFailure { exception ->
                println("GET Ring Error: ${exception.message}")
            }
        }
    }


    private fun parseAndDisplayData(jsonString: String) {
        try {
            val jsonObject = JSONObject(jsonString)
            val listArray = jsonObject.getJSONArray("list")
            val records = mutableListOf<RingRecord>()

            for (i in 0 until listArray.length()) {
                val item = listArray.getJSONObject(i)
                val record = RingRecord(
                    fid = item.getString("fid"),
                    has_preview = item.getInt("has_preview"),
                    ringtime = item.getLong("ringtime"),
                    face_score = item.getInt("face_score"),
                    op_type = item.getInt("op_type"),
                    bid = item.getString("bid")
                )
                records.add(record)
            }

            adapter.setData(records)

            // 显示/隐藏空状态
            if (records.isEmpty()) {
                tvEmpty.visibility = TextView.VISIBLE
                recyclerView.visibility = RecyclerView.GONE
            } else {
                tvEmpty.visibility = TextView.GONE
                recyclerView.visibility = RecyclerView.VISIBLE
            }

        } catch (e: Exception) {
            e.printStackTrace()
            tvEmpty.text = "数据加载失败"
            tvEmpty.visibility = TextView.VISIBLE
            recyclerView.visibility = RecyclerView.GONE
        }
    }

    private fun showRecordDetail(record: RingRecord) {
        // 跳转到详情页面或显示详情对话框
        // Intent(this, RingRecordDetailActivity::class.java).apply {
        //     putExtra("ring_record", record)
        //     startActivity(this)
        // }

        // 简单显示Toast
        android.widget.Toast.makeText(
            this,
            "查看记录: ${record.getOpenLockMethod()} - ${record.getFormattedTime()}",
            android.widget.Toast.LENGTH_SHORT
        ).show()
    }
}